﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Reactive.Linq;

namespace PiviotViewerSLViewer
{
    public class PSWAccess
    {
        public PSWAccess()
        {
            HTTPBase = "http://deeptalk.phys.washington.edu/PivotWeb";
        }

        /// <summary>
        /// What is the HTTP base value?
        /// </summary>
        public string HTTPBase { get; set; }

        /// <summary>
        /// Create a web request that then will get used by others.
        /// </summary>
        /// <param name="what"></param>
        /// <param name="method"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private WebRequest CreateRequest(string what, string method, params Tuple<string, string>[] args)
        {
            var urlbase = string.Format("{0}/api/{1}", HTTPBase, what);
            if (args.Length > 0)
            {
                char addon = '?';
                foreach (var arg in args)
                {
                    urlbase = string.Format("{0}{1}{2}={3}", urlbase, addon, arg.Item1, arg.Item2);
                    addon = '&';
                }
            }
            var req = WebRequest.Create(urlbase);
            req.Method = method;

            return req;
        }

        /// <summary>
        /// Return the collection of the name.
        /// </summary>
        /// <param name="cID"></param>
        /// <returns></returns>
        public IObservable<string> GetCollectionName(int cID)
        {
            var req = CreateRequest("Collections", "GET", Tuple.Create("id", cID.ToString()));

            return Observable.FromAsyncPattern<WebResponse>(req.BeginGetResponse, req.EndGetResponse)()
                .Select(wr =>
                {
                    using (var reader = new StreamReader(wr.GetResponseStream()))
                    {
                        var r = JsonConvert.DeserializeObject(reader.ReadToEnd()) as Newtonsoft.Json.Linq.JContainer;
                        return (string)r["Name"];
                    }
                });
        }

        /// <summary>
        /// Return the description of the name.
        /// </summary>
        /// <param name="cID"></param>
        /// <returns></returns>
        internal IObservable<string> GetCollectionDescription(int cID)
        {
            var req = CreateRequest("CollectionProperties", "GET", Tuple.Create("cId", cID.ToString()), Tuple.Create("propName", "Description"));

            return Observable.FromAsyncPattern<WebResponse>(req.BeginGetResponse, req.EndGetResponse)()
                .Select(wr =>
                {
                    using (var reader = new StreamReader(wr.GetResponseStream()))
                    {
                        return JsonConvert.DeserializeObject(reader.ReadToEnd()) as string;
                    }
                });
        }
    }
}
